import os
import time
from itertools import zip_longest

import pandas
import requests
from utils import root_dir
from utils.log_util import logger

# 登录接口
json = {
    "account": "ceshi",
    "userPwd": "123456",
    "loginType": 1
}
response = requests.post(url="http://192.168.1.45:8083/api/login", json=json)
if response.status_code == 200:
    token = response.json()['data']['token']
    tenant_id = response.json()['data']['tenantId']
    logger.debug(f"账号登录成功")
else:
    logger.error(f"账号登录失败,报错为{response.text}")

# 获取headers
headers = {
    "X-Api-Token": f"Bearer {token}",
}

# 获取数据
files_path = os.sep.join([root_dir, 'files'])
df = pandas.read_excel(os.sep.join([files_path, 'data.xlsx']), na_values=['nan'], keep_default_na=False)
names = df['姓名']
ssns = df['身份证号']
amounts = df['借款金额']
prednos = df['还款期数']
hkmoney1s = df['第一期应还总额']
hkPrincipal1s = df['第一期本金']
hkInterest1s = df['第一期利息']
hkmoney2s = df['第二期应还总额']
hkPrincipal2s = df['第二期本金']
hkInterest2s = df['第二期利息']
hkmoney3s = df['第三期应还总额']
hkPrincipal3s = df['第三期本金']
hkInterest3s = df['第三期利息']
hkmoney4s = df['第四期应还总额']
hkPrincipal4s = df['第四期本金']
hkInterest4s = df['第四期利息']
hkmoney5s = df['第五期应还总额']
hkPrincipal5s = df['第五期本金']
hkInterest5s = df['第五期利息']
hkmoney6s = df['第六期应还总额']
hkPrincipal6s = df['第六期本金']
hkInterest6s = df['第六期利息']

for (name, ssn, amount, predno,
     hkmoney1, hkPrincipal1, hkInterest1,
     hkmoney2, hkPrincipal2, hkInterest2,
     hkmoney3, hkPrincipal3, hkInterest3,
     hkmoney4, hkPrincipal4, hkInterest4,
     hkmoney5, hkPrincipal5, hkInterest5,
     hkmoney6, hkPrincipal6, hkInterest6) in (
        zip_longest(names, ssns, amounts, prednos,
                    hkmoney1s, hkPrincipal1s, hkInterest1s,
                    hkmoney2s, hkPrincipal2s, hkInterest2s,
                    hkmoney3s, hkPrincipal3s, hkInterest3s,
                    hkmoney4s, hkPrincipal4s, hkInterest4s,
                    hkmoney5s, hkPrincipal5s, hkInterest5s,
                    hkmoney6s, hkPrincipal6s, hkInterest6s)):
    logger.info(f"当前处理: 姓名 - {name}")

    # 建立初审订单
    json = {
        "mainBorrowerType": 1,  # 主借人类型
        "collectingAccountType": 1,  # 收款账户类型
        "orderFiles": [],
        "inputType": 2,  # 订单创建来源 不用改
        "unitsType": "MONTH",
        "mortgageHouseList": [],
        "contactList": [
            {
                "orderNo": 1,
                "contactName": "1",  # 第一个联系人姓名
                "contactPhone": "13111111111",  # 第一个联系人电话
                "contactRelation": "1",  # 第一个联系人关系 1、父母 2、配偶 3、子女 4、亲属 5、朋友 6、同事 7、兄弟 8、兄妹 9、姐妹 10、姐弟 11、其他
                "cusId": 1,
                "orderId": 1
            },
            {
                "orderNo": 1,
                "contactName": "2",
                "contactPhone": "13222222222",
                "contactRelation": "2",
                "cusId": 1,
                "orderId": 1
            },
            {
                "orderNo": 1,
                "contactName": "3",
                "contactPhone": "13333333333",
                "contactRelation": "3",
                "cusId": 1,
                "orderId": 1
            }
        ],
        "orderFileIds": [],
        "bankOrderFileIds": [
            "4202",
            "4203"
        ],
        "bankOrderFiles": [
            {
                "id": "4202",
                "url": "https://capital-cloud-test.oss-cn-shenzhen.aliyuncs.com/2025-03-28"
                       "/7906d1a8f80a4e1bb3fcae9b57a0e4c612.png"
            },
            {
                "id": "4203",
                "url": "https://capital-cloud-test.oss-cn-shenzhen.aliyuncs.com/2025-03-28"
                       "/17c5b9a12fd3452d9e66a8b5acff85fe13.png"
            }
        ],
        "customer": {
            "type": 2,  # 客户类型 1、自雇 2、授薪
            "fileIds": [
                "4200",
                "4201"
            ],
            "fileList": [
                {
                    "id": "4200",
                    "url": "https://capital-cloud-test.oss-cn-shenzhen.aliyuncs.com/2025-03-28"
                           "/dff616d58dd044648fc303043dd3011510.jpg"
                },
                {
                    "id": "4201",
                    "url": "https://capital-cloud-test.oss-cn-shenzhen.aliyuncs.com/2025-03-28"
                           "/bdc5b6f4ad9847feafb5b958e725157c11.png"
                }
            ],
            "businessFileIds": [],
            "businessFileList": [],
            "otherFiles": [
                {
                    "bizType": "BUSINESS_LOCATION"
                },
                {
                    "bizType": "BUSINESS_FLOW"
                },
                {
                    "bizType": "LEASE_CONTRACT"
                }
            ],
            "otherFileIds": [],
            "workLongType": "MONTH",
            "name": f"{name}",  # 姓名
            "idCard": f"{ssn}",  # 身份证号
            "idCardAddress": "身份证地址",  # 身份证地址
            "birth": "1999-12-31",  # 生日
            "sex": 1,  # 性别 1、男 2、女
            "idCardExpirationStart": "2000-01-01",  # 身份证有效期开始时间
            "idCardExpirationEnd": "2030-01-01",  # 身份证有效期结束时间
            "phone": 13888888888,  # 手机号码
            "domicile": 1,  # 居住地类型 1、本地 2、外地
            "addressTime": 2,  # 居住时间类型 1、 months、月 2、years、年
            "marriageStatus": 1,
            "degree": "3",  # 学历 3、高中及中专 7、大专 8、本科 12、研究生及以上 2、其他
            "address": "天安门",  # 现居地地址
            "workplaceName": "单位地址",
            "provinceId": 1,  # 居住地时长：1、一年以内 2、一到三年 3、三到五年 4、五年以上
            "cityId": 3216,  # 城市id 不改
            "districtId": 2  # 区id 不改
        },
        "capitalId": "252628196990",  # 资金方id
        "prodId": "16",  # 产品id
        "modeId": "252628082848",  # 配资方案id
        "loanMoney": int(amount),  # 借贷金额
        "loanUnit": int(predno),  # 借贷期限
        "hkType": 1,  # 还款方式
        "dkUse": "借贷用途",  # 借贷用途
        "accountName": "账户名",  # 还款账户名
        "bankName": "开户行",  # 开户行
        "reservedPhone": "13900000000",  # 银行卡手机号
        "bankNo": "11027810000008",  # 银行卡号
        "remark": "备注"  # 备注
    }
    response = requests.post(url="http://192.168.1.45:8083/api/order/agentOrderConfirm", headers=headers,
                             json=json)
    if response.status_code == 200:
        logger.debug(f"姓名{name}的初审订单已提交")
    else:
        logger.error(f"姓名{name}的初审订单提交失败,报错为{response.text}")

    # 获取订单号
    json = {
        "pageNum": 1, "pageSize": 1
    }
    response = requests.post(url="http://192.168.1.45:8083/api/order/agentPage", headers=headers, json=json)
    if response.status_code == 200:
        order_no = response.json()["data"]["list"][0]["id"]
        logger.debug(f"姓名{name}的初审订单号是{order_no}")
    else:
        logger.error(f"姓名{name}的初审订单号获取失败,报错为{response.text}")

    # 通过初审
    json = {"approveStatus": "1",
            "firstApproveFileIds": [],
            "firstApproveFiles": [],
            "orderId": f"{order_no}"}
    response = requests.post(url=f"http://192.168.1.45:8083/api/ylcOrderApprove/first/{order_no}",
                             headers=headers, json=json)
    if response.status_code == 200:
        logger.debug(f"姓名{name}的初审订单已通过,{response.text}")
    else:
        logger.error(f"姓名{name}的初审订单通过失败,报错为{response.text}")
    time.sleep(3)

    # # 通过复审
    # json = {
    #     "creditDate": "2025-03-07",
    #     "idCard": f"{ssn}",
    #     "applyFlg": "Y",
    #     "applyReason": "",
    #     "reportFile": "https://123.com/",
    #     "customerName": f"{name}",
    #     "thirdNo": f"{order_no}"
    # }
    # response = requests.post(url="http://192.168.1.45:8079/openapi/approveFirstData", json=json)
    # if response.status_code == 200:
    #     logger.debug(f"姓名{name},订单号{order_no}的订单已复审通过,{response.text}")
    # else:
    #     logger.error(f"姓名{name},订单号{order_no}的复审订单提交失败,报错为{response.text}")

    # # 通过终审
    # json = {
    #     "hasGuaranteeFee": 0,
    #     "loanAmount": f"{amount}",
    #     "loanRate": "0.02",
    #     "loanUnit": f"{predno}",  # 期数
    #     "repaymentType": 1,
    #     "guaranteeFeeType": 1,
    #     "serviceFeeType": 1,
    #     "serviceFee": "0",
    #     "approveStatus": "1",
    #     "orderId": f"{order_no}"
    # }
    # response = requests.post(url=f"http://192.168.1.45:8083/api/ylcOrderApprove/third/{order_no}", headers=headers,
    #                          json=json)
    # if response.status_code == 200:
    #     logger.debug(f"姓名{name},订单号{order_no}的订单已终审通过,{response.text}")
    # else:
    #     logger.error(f"姓名{name},订单号{order_no}的终审订单提交失败,报错为{response.text}")
    #
    # # 放款
    # json = {
    #     "custName": f"{name}",
    #     "identity": f"{ssn}",
    #     "loanAmount": int(amount),
    #     "loanFlg": "Y",
    #     "rate": 0.02,
    #     "fundingTime": "2025-03-25 08:00:00",
    #     "custPutoutDate": "2025-03-25",
    #     "thirdOrderNo": f"{order_no}",
    #     "withdrawalTerm": f'{predno}',
    #     "expire": "2025-09-25",
    #     "guaranteeFiles": "www.baidu.com",
    #     "loanContractNo": "7654321"
    # }
    # response = requests.post(url="http://192.168.1.45:8079/openapi/loanNoticeDemo", json=json)
    # if response.status_code == 200:
    #     logger.debug(f"姓名{name},订单号{order_no}的订单已放款,{response.text}")
    # else:
    #     logger.error(f"姓名{name},订单号{order_no}的放款失败,报错为{response.text}")
    #
    # # 生成还款计划
    # repayment_fields = []
    # data_sets = [
    #     (hkmoney1, hkPrincipal1, hkInterest1),
    #     (hkmoney2, hkPrincipal2, hkInterest2),
    #     (hkmoney3, hkPrincipal3, hkInterest3),
    #     (hkmoney4, hkPrincipal4, hkInterest4),
    #     (hkmoney5, hkPrincipal5, hkInterest5),
    #     (hkmoney6, hkPrincipal6, hkInterest6)
    # ]
    #
    # for money, principal, interest in data_sets:
    #     try:
    #         repayment_fields.append((int(money), int(principal), int(interest)))
    #     except (ValueError, TypeError):
    #         continue
    #
    # json = []
    # for i in range(int(predno)):
    #     json.append({
    #         "thirdNo": f"{order_no}",
    #         "list": [
    #             {
    #                 "predNo": f"{i}",
    #                 "hkMoney": repayment_fields[i - 1][0],
    #                 "hasHkMoney": 0.0,
    #                 "hkPrincipal": repayment_fields[i - 1][1],
    #                 "hkInterest": repayment_fields[i - 1][2],
    #                 "hkTime": "2025-01-16",
    #                 "hkStatus": 1
    #             }
    #         ]
    #     })
    # response = requests.post(url="http://192.168.1.45:8079/openapi/syncHkPlanDemo", json=json)
    # if response.status_code == 200:
    #     logger.debug(f"姓名{name},订单号{order_no}的还款计划已生成,{response.text}")
    # else:
    #     logger.error(f"姓名{name},订单号{order_no}的还款计划生成失败,报错为{response.text}")
    #
    # time.sleep(3)
    #
    # # 还款
    # json = {
    #     "thirdOrderNo": f"{order_no}",
    #     "loanFiles": "",
    #     "list": [
    #         {
    #             "predNo": 1,
    #             "hkMoney": 5000,
    #             "thirdNo": f"{order_no}",
    #             "repaymentType": 1,
    #             "principal": 4000,
    #             "interest": 1000,
    #             "repaymentFee": 0,
    #             "penalty": 0,
    #             "hkTime": "2025-03-07 00:00:00",
    #             "cleanFlg": "1",
    #             "finishType": 1
    #         }
    #     ]
    # }
    # response = requests.post(url="http://192.168.1.45:8079/openapi/repaymentNoticeDemo", json=json)
